<template>
  <el-form
    ref="form"
    label-width="auto"
    label-position="top"
    class="dynamic-form"
    size="mini"
  >
    <el-row :gutter="10">
      <template v-if="controls&&controls.length>0">
        <template v-for="(control, index) in controls">
          <dynamicContainer
            v-if="control.type == 'container'"
            :control="control || {}"
            v-model="bindModel(control)[control.field]"
            :isEdit="isEdit"
            :key="index + 'container'"
            :isEditForm="isEditForm"
          ></dynamicContainer>
          <dynamicCol
            v-else
            :key="index"
            :control="control || {}"
            v-model="bindModel(control)[control.field]"
            :isEdit="isEdit"
            :isEditForm="isEditForm"
          >
          </dynamicCol>
        </template>
      </template>
      <el-input
        v-else
        v-model="valueString"
        :readonly="!isEdit"
        type="textarea"
        size="normal"
        :rows="5"
      ></el-input>
    </el-row>
  </el-form>
</template>

<script>
import dynamicCol from "./components/dynamicCol.vue";
import dynamicContainer from "./components/dynamicContainer";

export default {
  components: { dynamicCol, dynamicContainer },
  props: {
    isEdit: {
      type: Boolean,
      default: false,
    },
  },
  watch: {
    value: {
      handler() {
        //this.load();
      },
      deep: true,
    },
    visible(newVal, oldVal) {
      if (!newVal && oldVal) this.hide();
    },
  },
  model: {
    prop: "value",
    event: "change",
  },
  data() {
    return {
      loading: false,
      visible: false,
      defaultLabelWidth: "150px",
      isEditForm: false,
      value: {},
      valueString:"",
      controls: [
        {
          span: 12,
          type: "empty",
          field: "field",
          label: "label",
          default: "",
          options: [],
        },
      ],
    };
  },
  methods: {
    bindModel(control) {
      if (!control) control = {};
      if (!this.value[control.field])
        this.$set(this.value, control.field, control.default);
      return this.value;
    },
    setValue(controls, newValue) {
      this.valueString = JSON.stringify(newValue);
      this.$set(this, "value", newValue);
      this.controls = [];
      let _this = this;
      this.$nextTick(() => {
        this.controls = controls;
      });
      
    },
    getValue() {
      if(this.controls&&this.controls.length>0)
        return this.value;
        else{
          try{
            return JSON.parse(this.valueString)
          }catch(e){
            return {};
          }
        }
    },
  },
};
</script>

<style></style>
